package com.ruoyi.sales.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.ZcStock;
import com.ruoyi.sales.service.IZcStockService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品原布原料和品类类似部门管理的Controller
 */
@RestController
@RequestMapping("/sales/stock")
public class ZcStockController extends BaseController {
    @Autowired
    private IZcStockService zcStockService;

    /**
     * 获取列表
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:list')")
    @GetMapping("/list")
    public AjaxResult list(ZcStock stock)
    {
        List<ZcStock> stocks = zcStockService.selectStockList(stock);
        return success(stocks);
    }

    /**
     * 查询列表（排除节点）
     * springmvc控制器方法 用于处理ajax请求
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:list')")
    @GetMapping("/list/exclude/{stockId}")
    public AjaxResult excludeChild(@PathVariable(value = "stockId", required = false) Long stockId)
    {
        List<ZcStock> stocks = zcStockService.selectStockList(new ZcStock());
        // removeIf 删除满足给定谓词的此集合的所有元素
        // ArrayUtils.contains：检查分割后的字符串数组是否包含转换为字符串的stockId
        // 如果上述逻辑表达式的任何一部分为 true，则 removeIf 方法会移除当前正在检查的元素 s
        // 遍历 stocks 列表，并移除所有其 stockId 与传入的 stockId 相等
        // 或者其 ancestors 字段（经过分割后）包含传入的 stockId 的 ZcStock 对象
        stocks.removeIf(s -> s.getStockId().intValue() == stockId || ArrayUtils.contains(StringUtils.split(s.getAncestors(), ","), stockId + ""));
        return success(stocks);
    }

    /**
     * 根据编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:query')")
    @GetMapping(value = "/{stockId}")
    public AjaxResult getInfo(@PathVariable Long stockId)
    {
        return success(zcStockService.selectStockById(stockId));
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:add')")
    @Log(title = "原料品类管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ZcStock stock)
    {
        if (!zcStockService.checkStockNameUnique(stock))
        {
            return error("新增原料品类'" + stock.getStockName() + "'失败，原料品类名称已存在");
        }
//        stock.setCreateBy(getUsername());
        return toAjax(zcStockService.insertStock(stock));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:edit')")
    @Log(title = "原料品类管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ZcStock stock)
    {
        Long stockId = stock.getStockId();
        if (!zcStockService.checkStockNameUnique(stock))
        {
            return error("修改原料品类'" + stock.getStockName() + "'失败，原料品类名称已存在");
        }
        else if (stock.getParentId().equals(stockId))
        {
            return error("修改原料品类'" + stock.getStockName() + "'失败，上级不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, stock.getStatus()) && zcStockService.selectNormalChildrenStockById(stockId) > 0)
        {
            return error("该原料品类包含未停用的子原料品类！");
        }
//        stock.setUpdateBy(getUsername());
        return toAjax(zcStockService.updateStock(stock));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:remove')")
    @Log(title = "原料品类管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{stockId}")
    public AjaxResult remove(@PathVariable Long stockId)
    {
        if (zcStockService.hasChildByStockId(stockId))
        {
            return warn("存在下级原料品类,不允许删除");
        }
//        if (zcStockService.checkStockExistUser(stockId))
//        {
//            return warn("部门存在用户,不允许删除");
//        }
        return toAjax(zcStockService.deleteStockById(stockId));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('sales:stock:edit')")
    @Log(title = "产品原料品类", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody ZcStock stock)
    {
        Long stockId = stock.getStockId();
        if (StringUtils.equals(UserConstants.DEPT_DISABLE, stock.getStatus()) && zcStockService.selectNormalChildrenStockById(stockId) > 0)
    {
        return error("该原料品类包含未停用的子原料品类！");
    }
        return toAjax(zcStockService.updateStockStatus(stock));
    }
}
